//
//  Created by matt on 28/09/12.
//

#import "ButtonPhotoBox.h"
#import "UIImageExtras.h"
#import "UIButton+WebCache.h"
#import <QuartzCore/QuartzCore.h>
#import "SDWebImageDecoder.h"

@implementation ButtonPhotoBox

//#define SPINNER_TAG 100

#pragma mark - Init

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.95 alpha:1];
        
        self.layer.shadowColor = [UIColor colorWithWhite:0.12 alpha:1].CGColor;
        self.layer.shadowOffset = CGSizeMake(0, 0.5);
        self.layer.shadowRadius = 1;
        self.layer.shadowOpacity = 1;
        
//        UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
//        spinner.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
//        spinner.color = UIColor.lightGrayColor;
//        spinner.tag = SPINNER_TAG;
//        [spinner startAnimating];
//        [self addSubview:spinner];
    }
    return self;
}

-(void)startIndicator:(BOOL)isStart{
//    UIActivityIndicatorView *spinner = self.subviews.lastObject;
//    if(isStart)
//        [spinner startAnimating];
//    else 
//        [spinner stopAnimating];
}

-(void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state{  
    __block UIImage *img = image;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        img = [img imageByScalingAndCroppingForSize:CGSizeMake(self.frame.size.width*2, self.frame.size.height*2)];
        img = [UIImage decodedImageWithImage:img];
        dispatch_async(dispatch_get_main_queue(), ^{
            [super setBackgroundImage:img forState:state]; 
        });
        
    });
    
//    if(image)
//        [self startIndicator:FALSE];
}

-(void)download:(NSString*)url_string{
    __unsafe_unretained id weakSelf = self;

    [self setImageWithURL:[NSURL URLWithString:url_string] placeholderImage:nil success:^(UIImage *image, BOOL cached) {
        [weakSelf setBackgroundImage:image forState:UIControlStateNormal];
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - Layout

- (void)layoutSubviews {
  [super layoutSubviews];
  self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
}



@end
